package com.ssm.sport.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssm.sport.entity.Shipping;
import com.ssm.sport.mapper.ShippingMapper;
import com.ssm.sport.service.OrderService;
import com.ssm.sport.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private ShippingMapper shippingMapper;

    /**
     * 创建订单 - 表单提交方式，直接重定向到订单详情页
     * 这个方法用于处理传统表单提交，不返回JSON
     */
    @PostMapping("/create")
    public String createOrderForm(
            @RequestParam(value = "shippingId", required = true) Integer shippingId,
            HttpSession session) {
        
        System.out.println("收到表单提交创建订单请求，收货地址ID: " + shippingId);
        
        // 参数验证
        if (shippingId == null || shippingId <= 0) {
            System.out.println("收货地址ID无效: " + shippingId);
            return "redirect:/cart?error=收货地址ID无效";
        }
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            System.out.println("用户未登录，session中没有user对象");
            return "redirect:/login";
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        System.out.println("当前用户ID: " + userId);
        
        try {
            OrderVO orderVO = orderService.createOrder(userId, shippingId);
            System.out.println("订单创建成功，订单号: " + orderVO.getOrderNo());
            String redirectUrl = "redirect:/order/detail?orderNo=" + orderVO.getOrderNo();
            System.out.println("重定向到: " + redirectUrl);
            return redirectUrl;
        } catch (Exception e) {
            System.out.println("创建订单失败: " + e.getMessage());
            e.printStackTrace();
            // 重定向到购物车页面，并带上错误信息
            return "redirect:/cart?error=" + e.getMessage();
        }
    }
    
    /**
     * 创建订单 - AJAX方式，返回JSON
     */
    @PostMapping("/create/ajax")
    @ResponseBody
    public Map<String, Object> createOrderAjax(
            @RequestParam("shippingId") Integer shippingId,
            HttpSession session) {
        
        Map<String, Object> result = new HashMap<>();
        
        System.out.println("收到AJAX创建订单请求，收货地址ID: " + shippingId);
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            System.out.println("用户未登录，session中没有user对象");
            result.put("status", 0);
            result.put("msg", "用户未登录");
            return result;
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        System.out.println("当前用户ID: " + userId);
        
        try {
            OrderVO orderVO = orderService.createOrder(userId, shippingId);
            System.out.println("订单创建成功，订单号: " + orderVO.getOrderNo());
            result.put("status", 1);
            result.put("msg", "创建订单成功");
            result.put("data", orderVO);
        } catch (Exception e) {
            System.out.println("创建订单失败: " + e.getMessage());
            e.printStackTrace();
            result.put("status", 0);
            result.put("msg", "创建订单失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/cancel")
    @ResponseBody
    public Map<String, Object> cancelOrder(
            @RequestParam("orderNo") String orderNo,
            HttpSession session) {
        
        Map<String, Object> result = new HashMap<>();
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            result.put("status", 0);
            result.put("msg", "用户未登录");
            return result;
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        
        boolean success = orderService.cancelOrder(userId, orderNo);
        if (success) {
            result.put("status", 1);
            result.put("msg", "取消订单成功");
        } else {
            result.put("status", 0);
            result.put("msg", "取消订单失败");
        }
        
        return result;
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/detail")
    public String getOrderDetail(
            @RequestParam("orderNo") String orderNo,
            Model model,
            HttpSession session) {
        
        System.out.println("进入订单详情页面，订单号: " + orderNo);
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            System.out.println("用户未登录，即将重定向到登录页面");
            return "redirect:/login";
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        System.out.println("当前用户ID: " + userId);
        
        OrderVO orderVO = orderService.getOrderDetail(userId, orderNo);
        if (orderVO == null) {
            System.out.println("未找到订单信息，订单号: " + orderNo);
            return "redirect:/order/list";
        }
        
        System.out.println("获取到订单信息: " + orderVO.getOrderNo() + ", 状态: " + orderVO.getStatus());
        System.out.println("订单商品数量: " + (orderVO.getOrderItemVOList() != null ? orderVO.getOrderItemVOList().size() : 0));
        
        model.addAttribute("order", orderVO);
        System.out.println("正在返回订单详情页面视图: order_detail");
        return "order_detail";
    }
    
    /**
     * 获取订单列表页面
     */
    @GetMapping("/list")
    public String getOrderList(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            Model model,
            HttpSession session) {
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            return "redirect:/login";
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        
        Page<OrderVO> orderPage = orderService.getOrderList(userId, pageNum, pageSize);
        
        model.addAttribute("orders", orderPage.getRecords());
        model.addAttribute("pageInfo", orderPage);
        
        // 获取并清除session中的成功消息
        if (session.getAttribute("successMessage") != null) {
            model.addAttribute("successMessage", session.getAttribute("successMessage"));
            session.removeAttribute("successMessage");
        }
        
        return "order_list";
    }
    
    /**
     * 支付订单
     */
    @PostMapping("/pay")
    @ResponseBody
    public Map<String, Object> payOrder(
            @RequestParam("orderNo") String orderNo,
            HttpSession session) {
        
        Map<String, Object> result = new HashMap<>();
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            result.put("status", 0);
            result.put("msg", "用户未登录");
            return result;
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        
        boolean success = orderService.payOrder(userId, orderNo);
        if (success) {
            result.put("status", 1);
            result.put("msg", "支付成功");
        } else {
            result.put("status", 0);
            result.put("msg", "支付失败");
        }
        
        return result;
    }
    
    /**
     * 管理员 - 获取所有订单列表
     */
    @GetMapping("/admin/list")
    public String getAllOrderList(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            Model model,
            HttpSession session) {
        
        // 从session中获取role, 只有管理员才能访问
        Integer role = (Integer) session.getAttribute("role");
        if (role == null || role != 1) {
            return "redirect:/login";
        }
        
        Page<OrderVO> orderPage = orderService.getAllOrderList(pageNum, pageSize);
        
        model.addAttribute("orders", orderPage.getRecords());
        model.addAttribute("pageInfo", orderPage);
        
        return "admin/order_list";
    }
    
    /**
     * 管理员 - 发货
     */
    @PostMapping("/admin/send")
    @ResponseBody
    public Map<String, Object> sendOrder(
            @RequestParam("orderNo") String orderNo,
            HttpSession session) {
        
        Map<String, Object> result = new HashMap<>();
        
        // 从session中获取role, 只有管理员才能访问
        Integer role = (Integer) session.getAttribute("role");
        if (role == null || role != 1) {
            result.put("status", 0);
            result.put("msg", "没有管理员权限");
            return result;
        }
        
        boolean success = orderService.sendOrder(orderNo);
        if (success) {
            result.put("status", 1);
            result.put("msg", "发货成功");
        } else {
            result.put("status", 0);
            result.put("msg", "发货失败");
        }
        
        return result;
    }

    /**
     * 创建订单 - 最简单方式，直接处理字符串参数
     */
    @PostMapping("/create-simple")
    public String createOrderSimple(
            HttpSession session,
            @RequestParam("shippingId") String shippingIdStr) {
        
        System.out.println("收到简单提交创建订单请求，原始收货地址ID参数: " + shippingIdStr);
        
        // 参数验证和转换
        Integer shippingId = null;
        try {
            shippingId = Integer.parseInt(shippingIdStr);
        } catch (NumberFormatException e) {
            System.out.println("收货地址ID转换失败: " + shippingIdStr);
            return "redirect:/cart?error=收货地址ID无效，请重新选择";
        }
        
        if (shippingId <= 0) {
            System.out.println("收货地址ID无效: " + shippingId);
            return "redirect:/cart?error=收货地址ID无效";
        }
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            System.out.println("用户未登录，session中没有user对象");
            return "redirect:/login";
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        System.out.println("当前用户ID: " + userId);
        
        try {
            OrderVO orderVO = orderService.createOrder(userId, shippingId);
            System.out.println("简单订单创建成功，订单号: " + orderVO.getOrderNo());
            return "redirect:/order/detail?orderNo=" + orderVO.getOrderNo();
        } catch (Exception e) {
            System.out.println("简单创建订单失败: " + e.getMessage());
            e.printStackTrace();
            return "redirect:/cart?error=" + e.getMessage();
        }
    }

    /**
     * 创建订单 - 备用方法，使用GET请求（仅用于测试，生产环境应删除）
     */
    @GetMapping("/create")
    public String createOrderGet(
            @RequestParam("shippingId") String shippingIdStr,
            HttpSession session) {
        
        System.out.println("收到GET请求创建订单（备用方法），收货地址ID参数: " + shippingIdStr);
        
        // 参数验证和转换
        Integer shippingId = null;
        try {
            shippingId = Integer.parseInt(shippingIdStr);
        } catch (NumberFormatException e) {
            System.out.println("收货地址ID转换失败: " + shippingIdStr);
            return "redirect:/cart?error=收货地址ID无效，请重新选择";
        }
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            System.out.println("用户未登录，session中没有user对象");
            return "redirect:/login";
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        System.out.println("当前用户ID: " + userId);
        
        try {
            OrderVO orderVO = orderService.createOrder(userId, shippingId);
            System.out.println("备用方法订单创建成功，订单号: " + orderVO.getOrderNo());
            return "redirect:/order/detail?orderNo=" + orderVO.getOrderNo();
        } catch (Exception e) {
            System.out.println("备用方法创建订单失败: " + e.getMessage());
            e.printStackTrace();
            return "redirect:/cart?error=" + e.getMessage();
        }
    }

    /**
     * 创建订单 - 固定ID方法，直接处理硬编码ID
     */
    @GetMapping("/createWithId")
    public String createOrderWithFixedId(HttpSession session, @RequestParam(value = "id", required = false) String idStr) {
        // 使用传入的固定ID值
        Integer shippingId = null;
        
        try {
            // 处理空字符串或null的情况
            if (idStr == null || idStr.trim().isEmpty()) {
                // 从session中获取用户
                Object userObj = session.getAttribute("user");
                if (userObj == null) {
                    System.out.println("用户未登录，session中没有user对象");
                    return "redirect:/login";
                }
                
                // 获取用户ID
                Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
                
                // 尝试获取默认地址
                Shipping defaultShipping = shippingMapper.selectDefaultShipping(userId);
                if (defaultShipping != null) {
                    shippingId = defaultShipping.getId();
                    System.out.println("ID参数为空，使用默认地址ID: " + shippingId);
                } else {
                    // 尝试获取用户的第一个地址
                    List<Shipping> userAddresses = shippingMapper.selectByUserId(userId);
                    if (!CollectionUtils.isEmpty(userAddresses)) {
                        shippingId = userAddresses.get(0).getId();
                        System.out.println("ID参数为空，使用第一个地址ID: " + shippingId);
                    } else {
                        System.out.println("用户没有收货地址");
                        return "redirect:/cart?error=Please+add+shipping+address+first";
                    }
                }
            } else {
                // 正常解析ID
                shippingId = Integer.parseInt(idStr);
            }
            
            if (shippingId <= 0) {
                return "redirect:/cart?error=Invalid+shipping+address+ID";
            }
        } catch (NumberFormatException e) {
            System.out.println("ID参数转换失败: " + idStr);
            return "redirect:/cart?error=Invalid+ID+format";
        }
        
        System.out.println("收到固定ID创建订单请求，使用ID: " + shippingId);
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            System.out.println("用户未登录，session中没有user对象");
            return "redirect:/login";
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        System.out.println("当前用户ID: " + userId);
        
        try {
            OrderVO orderVO = orderService.createOrder(userId, shippingId);
            System.out.println("固定ID方法订单创建成功，订单号: " + orderVO.getOrderNo());
            
            // 重定向到订单列表页面，避免可能的视图文件缺失
            session.setAttribute("successMessage", "订单创建成功，订单号: " + orderVO.getOrderNo());
            return "redirect:/order/list";
        } catch (Exception e) {
            System.out.println("固定ID方法创建订单失败: " + e.getMessage());
            e.printStackTrace();
            // 避免中文编码问题，使用英文错误信息
            return "redirect:/cart?error=Failed+to+create+order.+Please+check+address+ID";
        }
    }

    /**
     * 直接提交订单 - 极简版
     * 用于从checkout.jsp页面直接提交订单
     */
    @PostMapping("/direct-submit")
    public String directSubmitOrder(
            @RequestParam("shippingId") Integer shippingId,
            HttpSession session) {
        
        System.out.println("收到直接提交订单请求，收货地址ID: " + shippingId);
        
        // 参数验证
        if (shippingId == null || shippingId <= 0) {
            System.out.println("收货地址ID无效: " + shippingId);
            return "redirect:/cart?error=Invalid+shipping+address";
        }
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            System.out.println("用户未登录，session中没有user对象");
            return "redirect:/login";
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        System.out.println("当前用户ID: " + userId);
        
        try {
            // 创建订单
            OrderVO orderVO = orderService.createOrder(userId, shippingId);
            System.out.println("订单直接提交成功，订单号: " + orderVO.getOrderNo());
            
            // 重定向到订单详情页
            return "redirect:/order/detail?orderNo=" + orderVO.getOrderNo();
        } catch (Exception e) {
            System.out.println("创建订单失败: " + e.getMessage());
            e.printStackTrace();
            // 避免URL编码问题，使用英文错误信息
            return "redirect:/cart?error=Order+creation+failed";
        }
    }

    /**
     * 获取订单详情 - REST风格路径
     */
    @GetMapping("/detail/{orderNo}")
    public String getOrderDetailRest(
            @PathVariable("orderNo") String orderNo,
            Model model,
            HttpSession session) {
        
        System.out.println("REST风格路径访问订单详情，订单号: " + orderNo);
        
        // 从session中获取用户
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            return "redirect:/login";
        }
        
        // 获取用户ID
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        
        OrderVO orderVO = orderService.getOrderDetail(userId, orderNo);
        if (orderVO == null) {
            return "redirect:/order/list";
        }
        
        model.addAttribute("order", orderVO);
        return "order_detail";
    }
} 